<template>
  <div class="home">
    <div>
      <button @click="onClick">点击添加</button>
      <button @click="onClickButton">点击跳转about</button>
    </div>
    <div class="content" ref="content">
      <div v-for="(item,index) in items"
      :key="index"
      class="item"
      :style="{left:item.x+'px',top:item.y+'px'}"
      @touchstart="onTouchStart"></div>
    </div>
  </div>
</template>

<script>
// @ is an alias to /src

export default {
  name: 'Home',
  components: {
    
  },
  data(){
    return{
      items:[]
    }
  },
  methods:{
    onClick(){
      let contentEle = this.$refs.content;
      let xMaxScope = contentEle.offsetWidth-100;
      let xMinScope = 0;
      let yMaxScope = contentEle.offsetHeight-100;
      let yMinScope = 0;
      let x = this.getRandom(xMinScope,xMaxScope);
      let y = this.getRandom(yMinScope,yMaxScope);
      let ele = {
        x:x,
        y:y
      }
      this.items.push(ele)
    },
    getRandom(min,max){
      return Math.random() * (max - min + 1) + min; 
    },
    onTouchStart(event){
      console.log(event)
      //获取当前事件发生元素
      let target = event.target;
      let contentEle = this.$refs.content;
      //获取鼠标/手指在当前屏幕的x轴、y轴坐标
      let touchX = event.touches[0].pageX;
      let touchY = event.touches[0].pageY;
      //获取拖动元素的初始原点
      let eleX = target.offsetLeft;
      let eleY = target.offsetTop;
      
      let offsetX = touchX-eleX;
      let offsetY = touchY-eleY;

      document.addEventListener("touchmove",function(moveEvent){
        let moveX = moveEvent.touches[0].pageX;
        let moveY = moveEvent.touches[0].pageY;

        let newX  = moveX-offsetX;
        if(newX<=0){
          newX=0;
        }
        if(newX>=contentEle.offsetWidth-target.offsetWidth){
          newX = contentEle.offsetWidth-target.offsetWidth;
        }
        let newY = moveY-offsetY;
        if(newY<=0){
          newY=0;
        }
        if(newY>=contentEle.offsetHeight-target.offsetHeight){
          newY = contentEle.offsetHeight-target.offsetHeight;
        }
        target.style.left = newX+"px";
        target.style.top = newY+"px";
      })
    },
    onClickButton(){
      this.$router.push("/about")
    }
  }
}
</script>

<style scoped>
.content
{
  width: 100%;
  height: 300px;
  border: 1px solid red;
  position: relative;
}

.item
{
  width: 100px;
  height: 100px;
  background-color: red;
  position: absolute;
}
</style>
